import dayjs from "dayjs";
import { AxiosRequestConfig } from "axios";
import http from "./http";

export default class Utils {
    static deepClone(obj: any) {
        const newObj: any = Utils.isArray(obj) ? [] : {};

        for (const key in obj) {
            if (Reflect.has(obj, key)) {
                const item = obj[key];
                if (Utils.isObjOrArr(item)) {
                    newObj[key] = Utils.deepClone(item);
                } else if (Utils.isDate(item)) {
                    newObj[key] = new Date(item);
                } else {
                    newObj[key] = item;
                }
            }
        }
        return newObj;
    }

    static is(val: unknown, type: string) {
        return toString.call(val) === `[object ${type}]`;
    }

    static isString(val: unknown): val is string {
        return Utils.is(val, "String");
    }

    static isFunc(val: unknown): val is Function {
        return typeof val === "function";
    }

    static isArray(val: any): val is Array<any> {
        return val && Array.isArray(val);
    }

    static isObject(val: any): val is Record<any, any> {
        return val !== null && Utils.is(val, "Object");
    }

    static isDate(val: unknown): val is Date {
        return Utils.is(val, "Date");
    }

    static isObjOrArr(val: unknown): boolean {
        return typeof val === "object";
    }

    static isEmpty(val: string | null | undefined): boolean {
        if (val === null || val === "" || val === undefined) {
            return true;
        }
        return false;
    }

    //格式化 请求URI
    static formatUrl<T>(data: T, removeItem?: string): string {
        let uri = "";
        let key: keyof T;
        for (key in data) {
            if (removeItem && key == removeItem) continue;
            if (data[key] === undefined || data[key] === null) {
                continue;
            }
            uri = uri + key.toString() + "=" + data[key] + "&";
        }
        uri = uri.substring(0, uri.length - 1);
        return uri;
    }

    //判断是否需要拼接地址
    static getFullUrl(url?: string): string {
        if (Utils.isEmpty(url)) return "";
        if (url!.indexOf("http:") > -1 || url!.indexOf("https:") > -1) {
            return url!;
        }
        return url!;
    }

    //判断是否需要拼接地址
    static getLocalImageSrc(name?: string): string {
        if (Utils.isEmpty(name)) return "";
        return new URL(`../assets/${name}`, import.meta.url).href;
    }

    //当前平台是否为iOS
    static isIOS(): boolean {
        const u = navigator.userAgent;
        const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        return isIOS;
    }

    static createElement(tagName: string, className: string) {
        const element = document.createElement(tagName);
        className && (element.className = className);
        return element;
    }
}
